import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main2 {

    public static int n;
    public static int k;
    public static int[][] arr;
    public static int[] dx = new int[]{-1, -1, 0, 1, 1, 1, 0, -1};
    public static int[] dy = new int[]{0, 1, 1, 1, 0, -1, -1, -1};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        n = sc.nextInt();
        k = sc.nextInt();

        arr = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                arr[i][j] = sc.nextInt();
            }
        }

        boolean[][] flag = new boolean[n][n];

        flag[0][0] = true;

        List<Integer> list = new ArrayList<>();

        if (!dfs(0, 0, 0, flag, list)) {
            System.out.println(-1);
        }

        sc.close();
    }

    /**
     * (x, y) 对应 arr 下标
     * @param x
     * @param y
     * @param count 对应当前遍历到 0-k 中的哪个元素了
     * @param flag 标记数组
     */
    public static boolean dfs(int x, int y, int count, boolean[][] flag, List<Integer> list) {

        if (x == n - 1 && y == n - 1 && list.size() == n * n - 1) {
            for (int num : list) {
                System.out.print(num);
            }
            return true;
        }


        for (int i = 0; i < 8; i++) {
            int xx = x + dx[i];
            int yy = y + dy[i];
            if (xx >= 0 && xx < n && yy >= 0 && yy < n && !flag[xx][yy] && arr[xx][yy] == count) {
                //0， 2， 4， 6 不需要判断路径是否交叉
                if (i % 2 != 0) {
                    //判断路径是否交叉
                    int i1 = 0, i2 = 0;
                    if (i == 7) {
                        i1 = 6;
                        i2 = 0;
                    } else {
                        i1 = i - 1;
                        i2 = i + 1;
                    }
                    if (!(flag[x + dx[i1]][y + dy[i1]] && flag[x + dx[i2]][y + dy[i2]])) {
                        list.add(i);
                        flag[xx][yy] = true;
                    }
                } else {
                    list.add(i);
                    flag[xx][yy] = true;
                }
            }
            if (dfs(xx, yy, (count + 1) % k, flag, list)) {
                return true;
            }
            flag[xx][yy] = false;  // 回溯
            list.remove(list.size() - 1);  // 回溯
        }
        return false;
    }

    public static boolean method(boolean[][] flag) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (!flag[i][j]) {
                    return false;
                }
            }
        }
        return true;
    }
}
